package com.iweb.utils;

import cn.hutool.core.bean.BeanUtil;
import com.iweb.poji.User;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class UserTable {
    private List<User> users;

    /**
     * 初始化
     */ {
        users = new ArrayList<>();
        users.add(new User(1, "jack", 20));
        users.add(new User(2, "tom", 22));
        users.add(new User(3, "ketty", 24));
        users.add(new User(4, "jerry", 21));
    }

    /**
     * 查询
     *
     * @return
     */
    public List<User> select() {
        return users;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public User select(Integer id) {
        List<User> list = users.stream().filter(user -> user.getId().equals(id)).collect(Collectors.toList());
        return list.size() == 1 ? list.get(0) : null;
    }

    /**
     * 添加
     *
     * @param user
     */
    public void insert(User user) {
        if (!users.contains(user)) {
            users.add(user);
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Integer id) {
        users = users.stream().filter(user -> !user.getId().equals(id)).collect(Collectors.toList());
    }

    /**
     * 修改
     *
     * @param user
     */
    public void update(User user) {
        AtomicInteger count = new AtomicInteger();
        users = users.stream().map(u -> {
            if (u.getId().equals(user.getId())) {
                BeanUtil.copyProperties(user, u);
                count.getAndIncrement();
            }
            return u;
        }).collect(Collectors.toList());
    }

}
